package com.liang.book.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;

import com.liang.book.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private static  long VALID_TIME = 60*1000;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
        ICaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight(), 4 ,4);
//        ICaptcha captcha = CaptchaUtil.createShearCaptcha(100, 40, 4 ,4);
        captcha.write(response.getOutputStream());
        response.setHeader("Prama","No-cache");
        response.setContentType("image/jpeg");
        System.out.println("生成的验证码"+captcha.getCode());

        session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
        response.getOutputStream().close();
//Servlet的OutputStream记得自行关闭哦！

    }
    @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session) {
        System.out.println("接收到captcha : " + captchaCode);

        if(!StringUtils.hasLength(captchaCode)) {
            return false;
        }
        String sessionCode = (String)session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long)session.getAttribute(captchaProperties.getSession().getDate());

        if(captchaCode.equalsIgnoreCase(sessionCode) && sessionDate != null && (System.currentTimeMillis() - sessionDate)  < VALID_TIME) {
            return true;
        }
        return false;
    }
}
